package com.example.student_blocket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UserProfileActivity extends Activity implements OnClickListener {
	
	private final String USER_PROFILE = Singleton.getInstance().getHOST() + "shop-app/get-owner-details.php";
	private final String UPDATE_USER = Singleton.getInstance().getHOST() + "shop-app/upadate-user.php";
	private TextView usernameView;
	private EditText passwordView;
	private EditText namesView;
	private EditText addressView;
	private EditText phoneView;
	private EditText emailView;
	private Button updateUser;
	private Button myAds;
	
	private String username;
	private String password;
	private String names;
	private String address;
	private String phone;
	private String email;
	private int updateState = 0;
	private final Misc misc = new Misc();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.activity_userprofile);
		iniGUIComponents();
		new LoadUserProfile().execute();
	}

	@Override
	public void onClick(View v) {
		if (v == updateUser) {
			if (updateState == 0) {
				updateState = 1;
				editableFields(true);
			} else {
				if (misc.validateFirstLastName(names) && misc.validateEmail(email)) {
					new UpdateUserProfile().execute();
				} else {
					if(!misc.validateFirstLastName(names)) {
						misc.showErrorMessage("First & Last Name field can NOT be empty!",getApplicationContext());
					} else if(!misc.validateEmail(email)) {
						misc.showErrorMessage("The email field can NOT ne empty or the email is incorrect!",getApplicationContext());
					} else {
						misc.showErrorMessage("Opppass!",getApplicationContext());
					}
				}
				updateState = 0;
			}
		} else if(v == myAds){
			startActivity(new Intent(UserProfileActivity.this, MyAdsActivity.class));
			finish();
		}
	}

	private void iniGUIComponents() {
		usernameView = (TextView) findViewById(R.id.textViewUsername);
		passwordView = (EditText) findViewById(R.id.updatePassword);
		namesView = (EditText) findViewById(R.id.updateFullName);
		addressView = (EditText) findViewById(R.id.updateAddress);
		phoneView = (EditText) findViewById(R.id.updatePhoneNumber);
		emailView = (EditText) findViewById(R.id.updateEmail);
		username = Singleton.getInstance().getUsername();
		updateUser = (Button) findViewById(R.id.btnUpdateUserProfile);
		myAds = (Button) findViewById(R.id.btnMyAds);
		updateUser.setOnClickListener(this);
		myAds.setOnClickListener(this);
		editableFields(false);
	}
	
	private void editableFields(Boolean isEditable){
		passwordView.setEnabled(isEditable);
		namesView.setEnabled(isEditable);
		addressView.setEnabled(isEditable);
		emailView.setEnabled(isEditable);
		phoneView.setEnabled(isEditable);
	}
	
	private void setUserProfile() {
		usernameView.setText(username);
		passwordView.setText(password);
		namesView.setText(names);
		addressView.setText(address);
		phoneView.setText(phone);
		emailView.setText(email);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_profile, menu);
		return true;
	}
	@Override
	public void onBackPressed() {
		startActivity(new Intent(UserProfileActivity.this, AdsActivity.class));
		finish();
	}
	private class LoadUserProfile extends AsyncTask<String, String, String> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(UserProfileActivity.this);
	        pDialog.setMessage("Loading Your Profile...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
		@Override
		protected String doInBackground(String... params) {
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
			values.add(new BasicNameValuePair("username", username));
            JSONObject json = jParser.makeHttpRequest(USER_PROFILE, values);
            try {
				int success = json.getInt("affected");
				if (success == 1) {
					names = json.getString("first_name") + " " + json.getString("last_name");
					address = json.getString("address");
					phone = json.getString("telephone");
					email = json.getString("email");
				} else {
					Intent i = new Intent(getApplicationContext(), AdsActivity.class);
					finish();
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
			} catch (Exception e) {
			}
			return null;
        }
 
		@Override
		protected void onPostExecute(String op) {
			pDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
				public void run() {
                	setUserProfile();
                }
            });
        }
	}
	
	private class UpdateUserProfile extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(UserProfileActivity.this);
	        pDialog.setMessage("Updating Your Profile...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
		@Override
		protected Boolean doInBackground(String... params) {
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
			values.add(new BasicNameValuePair("username", username));
			values.add(new BasicNameValuePair("password", passwordView.getText().toString()));
			String[] namesIn = namesView.getText().toString().split(" ");
	        String firstName = namesIn[0];
	        String lastName = namesIn[1];
			values.add(new BasicNameValuePair("first_name", firstName));
			values.add(new BasicNameValuePair("last_name", lastName));
			values.add(new BasicNameValuePair("address", addressView.getText().toString()));
			values.add(new BasicNameValuePair("telephone", phoneView.getText().toString()));
			values.add(new BasicNameValuePair("email", emailView.getText().toString()));
			
            JSONObject json = jParser.makeHttpRequest(UPDATE_USER, values);
            try {
				int success = json.getInt("affected");
				if (success == 1) {
					return true;
				} else {
					return false;
				}
			} catch (Exception e) {}
			return null;
        }
 
		@Override
		protected void onPostExecute(final Boolean op) {
			pDialog.dismiss();
            if (op) {
            	new LoadUserProfile().execute();
            	editableFields(false);
			} else {
				Intent i = new Intent(getApplicationContext(), AdsActivity.class);
				finish();
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(i);
			}
            
        }
	}

}
